package sgc.beans;

import java.io.IOException;
import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import sgc.struc.Req_Header;
import sgc.struc.Req_Position;

@ManagedBean(name = "purchaseReqBean")
@SessionScoped
public class PurchaseReqBean implements Serializable {

	private static final long serialVersionUID = 7243677153195728454L;
	private Req_Header header;
	private Req_Position position;
	private List<Req_Position> positions;
	private int conta;
	private String user_name;
	private String user_id;

	private DataSource ds;

	public PurchaseReqBean() {
		try {
			Context ctx = new InitialContext();
			ds = (DataSource) ctx.lookup("java:comp/env/jdbc/sgcweb");
		} catch (NamingException e) {
			e.printStackTrace();
		}
		header = new Req_Header();
		position = new Req_Position();
		positions = new ArrayList<Req_Position>();
		positions.clear();

		FacesContext context = FacesContext.getCurrentInstance();
		CheckUserBean cu = (CheckUserBean) context.getApplication()
				.evaluateExpressionGet(context, "#{checkUserBean}",
						CheckUserBean.class);

		user_name = cu.getUsuario().getDescrip();
		user_id = cu.getUsuario().getName();
		header.setSolicitante(user_name);

	}

	private int act_company() {
		int company;
		company = 0;
		try {
			FacesContext context = FacesContext.getCurrentInstance();
			CheckUserBean cu = (CheckUserBean) context.getApplication()
					.evaluateExpressionGet(context, "#{checkUserBean}",
							CheckUserBean.class);
			company = cu.getUsuario().getCompany_code();
		} catch (Exception e) {
		}
		return company;

	}

	public String reinit() {
		conta++;
		if (conta == 0) {
			conta = 1;
		}
		position = new Req_Position();
		position.setReq_pos(conta);
		return null;
	}

	public Req_Header getHeader() {
		return header;
	}

	public void setHeader(Req_Header header) {
		this.header = header;
	}

	public Req_Position getPosition() {
		return position;
	}

	public void setPosition(Req_Position position) {
		this.position = position;
	}

	public List<Req_Position> getPositions() {
		return positions;
	}

	public void setPositions(List<Req_Position> positions) {
		this.positions = positions;
	}

	private java.sql.Date convertDate(java.util.Date jDate) {
		java.sql.Date sqlDate;
		long t;

		if (jDate == null) {
			sqlDate = new java.sql.Date(0);
		} else {
			t = jDate.getTime();
			sqlDate = new java.sql.Date(t);
		}
		return sqlDate;
	}

	private String parseStr(String campo) {
		String delims = " - ";
		String[] tokens = campo.split(delims);

		return tokens[0];
	}

	private int parseInt(String campo) {
		String delims = " - ";
		String[] tokens = campo.split(delims);

		return Integer.parseInt(tokens[0]);
	}

	public void Save() throws SQLException {

		String aux_message;
		String aux_message_p;
		ResultSet result;
		CallableStatement cs;
		String simpleProc;
		Iterator<Req_Position> it;
		Req_Position posicion;
		int req_no;
		int req_pos_p;
		int req_pos;

		if (ds == null)
			throw new SQLException("Can't get data source");
		Connection con = ds.getConnection();
		if (con == null)
			throw new SQLException("Can't get database connection");

		// Cabecera de registro

		simpleProc = "{ CALL sp_addReqHeader(?,?,?,?,?,?,?) }";

		cs = con.prepareCall(simpleProc);
		cs.setDate(1, convertDate(header.getFec_sol()));
		cs.setDate(2, convertDate(header.getFec_req()));
		cs.setString(3, user_id);
		cs.setString(4, parseStr(header.getCecos()));
		cs.setString(5, parseStr(header.getSuplier()));
		cs.setString(6, header.getReq_deta());
		cs.setInt(7, act_company());

		cs.execute();
		result = cs.getResultSet();
		result.next();
		aux_message = result.getString(3);
		req_no = result.getInt(2);
		if (req_no == 0) {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, aux_message,
							null));
		} else {
			// Posiciones
			it = positions.iterator();
			req_pos = 0;
			while (it.hasNext()) {
				req_pos++;
				posicion = it.next();
				simpleProc = "{ CALL sp_addReqPosition(?,?,?,?,?) }";
				cs = con.prepareCall(simpleProc);

				cs.setInt(1, req_no);
				cs.setInt(2, req_pos);
				cs.setInt(3, parseInt(posicion.getMat_name()));
				cs.setDouble(4, posicion.getMat_cant());
				cs.setInt(5, act_company());

				cs.execute();
				result = cs.getResultSet();
				result.next();
				req_pos_p = result.getInt(3);
				aux_message_p = result.getString(4);
				if (req_pos_p == 0) {
					FacesContext.getCurrentInstance().addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_ERROR,
									aux_message_p, null));
				}
			}
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_INFO, aux_message,
							null));
			header = null;
			positions = null;

		}
	}

	public void back() throws IOException {
//		FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("purchaseReqBean");
		FacesContext.getCurrentInstance().getExternalContext()
		.redirect("faces/navegacion.xhtml");
	}
}
